package com.person.commons.security;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.person.base.model.BaseUser;
import com.person.commons.utils.Constants;
import com.person.sys.model.SysAsset;
import com.person.sys.service.SysAssetService;
import com.person.sys.service.SysFuncService;

/**
 * OA权限过滤器
 * @author yaolei
 * 
 */
public class AuthorityFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(AuthorityFilter.class);
	private String noPermissionURl = "";
	private String loginURL = "";
	private SysFuncService sysFuncService;
	private SysAssetService sysAssetService;
	
	
	public void setSysFuncService(SysFuncService sysFuncService) {
		this.sysFuncService = sysFuncService;
	}

	public void setSysAssetService(SysAssetService sysAssetService) {
		this.sysAssetService = sysAssetService;
	}

	/**
	 * 初始化
	 */
    public void init(FilterConfig arg0) throws ServletException {
	}

	public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;
		HttpSession session = request.getSession();
		String url = request.getServletPath();
		String contextPath = request.getContextPath();
		
		BaseUser user = (BaseUser)session.getAttribute(Constants.SESSION_USER);
		String[] func = (String[])session.getAttribute(Constants.ROLE_CODE);
		
		String[] asset = (String[])session.getAttribute(Constants.ASSET_CODE);
		
		loginURL = contextPath+"/";
		noPermissionURl = contextPath+"/commons/noPermission.jsp";
		
		if(url.startsWith("/index/user_login.action")
				|| url.startsWith("/loginindex.action") 
				|| url.startsWith("/front/")
				|| url.startsWith("/web/")
				||url.startsWith("/index!viewTop.action")
				||url.startsWith("/index!viewLeft.action")
				||url.startsWith("/index!viewMain.action")
				||url.startsWith("/index!viewNav.action")
				||url.startsWith("/user/user!preCreateUser")
				||url.startsWith("/user/user_register.action")
				||url.startsWith("/index!viewFoot.action")//如果用户进行登陆有关操作
			    ||url.startsWith("/user/user!controlPanel.action")){
			filterChain.doFilter(sRequest, sResponse);
			return;
		}else if(user == null){//用户没登陆
			sendLoginPage(response);
			return;
		}else if( func == null){
			sendNoPermissionPage(response);
			return;
		}else if(func != null && func.length == 0){
			sendNoPermissionPage(response);
			return;
		}else if(asset != null && asset.length > 0){
			
			for(int i=0;i<asset.length;i++){
				
				SysAsset sysAsset = sysAssetService.findByAssetId(asset[i]);
				
				if(sysAsset!= null && url.indexOf(sysAsset.getAssetLink()) != -1){
					sendNoPermissionPage(response);
					return;
				}else{
					filterChain.doFilter(sRequest, sResponse);
					return;
				}
				
			}
			
			
		}else{
			filterChain.doFilter(sRequest, sResponse);
			return;
		}
		
	}
	
	
	/**
	 * 导向无权限访问提示页面
	 * @param response
	 */
	public void sendNoPermissionPage(HttpServletResponse response)  {
		sendPage(response,noPermissionURl);
	}
	/**
	 * 导向登陆页面
	 * @param response
	 */
	public void sendLoginPage(HttpServletResponse response){
		sendPage(response,loginURL);
	}
	/**
	 * 顶层窗口打开页面
	 * @param response
	 * @param url 内容页面url
	 */
	private void sendPage(HttpServletResponse response,String url)  {
	    try{
	       response.setContentType("text/html;charset=UTF-8");
 	       PrintWriter out=response.getWriter();
 	       out.write("<script type='text/javascript'>");
  	       out.write("window.top.location.href=");
  	       out.write("'"+url+"'");
  	       out.write("</script>");
  	       out.flush();
  	       out.close();
	    }catch(Exception e){
	    	 e.printStackTrace();
	    	 log.error(e);
	    }
	}
}
